﻿using System;
using Autodesk.Revit.DB;

namespace YJKArch.DimensionModule
{
	internal class DimUtility
	{
		public static Element GetElementByReference(Autodesk.Revit.DB.Document doc, Reference refElem)
		{
			if (refElem.LinkedElementId != ElementId.InvalidElementId)
			{
				return (doc.GetElement(refElem.ElementId) as RevitLinkInstance).GetLinkDocument().GetElement(refElem.LinkedElementId);
			}
			return doc.GetElement(refElem.ElementId);
		}

		public static Reference GetReferenceByDoc(Autodesk.Revit.DB.Document doc, Reference refElem)
		{
			if (refElem.LinkedElementId != ElementId.InvalidElementId)
			{
				return refElem.CreateReferenceInLink();
			}
			return refElem;
		}

		public static Reference ConvertDimReference(Autodesk.Revit.DB.Document doc, Reference refElem)
		{
			Reference result = refElem;
			Element elementByReference = DimUtility.GetElementByReference(doc, refElem);
			Reference referenceByDoc = DimUtility.GetReferenceByDoc(doc, refElem);
			if (elementByReference.GetGeometryObjectFromReference(referenceByDoc) == null && refElem.LinkedElementId == ElementId.InvalidElementId)
			{
				result = new Reference(elementByReference);
			}
			return result;
		}
	}
}
